package com.qubuyer.business.mine.fragment

import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.qubuyer.R
import com.qubuyer.business.mine.adapter.MessageListAdapter
import com.qubuyer.business.mine.viewmodel.MsgViewModel
import com.qubuyer.core.app.MVVMFragment
import com.qubuyer.core.ext.dp
import com.qubuyer.customview.DecorationLLM
import com.qubuyer.databinding.FragmentMessageListPageBinding

class MessageListFragment : MVVMFragment<FragmentMessageListPageBinding, MsgViewModel>() {
    override fun onDataBinding(dataBinding: FragmentMessageListPageBinding) {
        dataBinding.host = this
    }

    override val viewModel: MsgViewModel by injectVMByFragment()

    override val layoutId: Int
        get() = R.layout.fragment_message_list_page

    private lateinit var adapter: MessageListAdapter

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        viewModel.type = arguments?.getInt("type") ?: 1
        adapter = MessageListAdapter(viewModel.type)
        viewDataBinding.rvList.layoutManager = LinearLayoutManager(mContext)
        viewDataBinding.rvList.addItemDecoration(
            DecorationLLM(
                mContext,
                DecorationLLM.VERTICAL_LIST,
                R.drawable.shape_recyclerview_divider,
                15.dp
            )
        )
        viewDataBinding.rvList.adapter = adapter
        viewDataBinding.srlRefresh.setOnRefreshListener { refreshLayout ->
            refreshLayout.resetNoMoreData()
            viewModel.refreshMsg { success, dataList, _, _ ->
                if (success) {
                    adapter.setDataList(dataList)
                    viewDataBinding.srlRefresh.finishLoadMore(0, true, dataList?.size ?: 0 < 10)
                } else {
                    viewDataBinding.srlRefresh.finishLoadMore(0, false, true)
                }
            }
        }
        viewDataBinding.srlRefresh.setOnLoadMoreListener {
            viewModel.loadMoreMsg { success, dataList, _, _ ->
                if (success) {
                    adapter.addDataList(dataList)
                    viewDataBinding.srlRefresh.finishLoadMore(0, true, dataList?.size ?: 0 < 10)
                } else {
                    viewDataBinding.srlRefresh.finishLoadMore(0, false, true)
                }
            }
        }
        viewDataBinding.srlRefresh.setEnableScrollContentWhenLoaded(true)
    }

    override fun hideProgressDialog() {
        viewDataBinding.srlRefresh.finishRefresh()
        viewDataBinding.srlRefresh.finishLoadMore()
        super.hideProgressDialog()
    }

    override fun needLazyLoad(): Boolean {
        return adapter.dataList.isEmpty()
    }

    override fun lazyLoad() {
        viewDataBinding.srlRefresh.autoRefresh()
    }
}